import React, { useState, useEffect } from 'react';
import { Table, Button, Space, message, Popconfirm, Card, Typography, Spin, Empty } from 'antd';
import { DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { RoutePlan } from '../types';
import { getAllRoutePlans, deleteRoutePlan } from '../services/routeService';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;

const RoutePlans: React.FC = () => {
  const [routePlans, setRoutePlans] = useState<RoutePlan[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const navigate = useNavigate();

  // 加载所有路线计划
  const loadRoutePlans = async () => {
    setLoading(true);
    try {
      const plans = await getAllRoutePlans();
      setRoutePlans(plans);
    } catch (error) {
      console.error('加载路线计划失败:', error);
      message.error('加载路线计划失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载
  useEffect(() => {
    loadRoutePlans();
  }, []);

  // 删除路线计划
  const handleDeletePlan = async (id: string) => {
    try {
      const success = await deleteRoutePlan(id);
      if (success) {
        message.success('路线计划删除成功');
        loadRoutePlans();
      } else {
        message.error('路线计划删除失败');
      }
    } catch (error) {
      console.error('删除路线计划失败:', error);
      message.error('删除路线计划失败');
    }
  };

  // 查看路线计划详情
  const handleViewPlan = (plan: RoutePlan) => {
    // 将计划保存到会话存储中
    sessionStorage.setItem('selectedRoutePlan', JSON.stringify(plan));
    // 导航到详情页面
    navigate('/route-detail');
  };

  // 格式化距离
  const formatDistance = (meters: number): string => {
    if (meters >= 1000) {
      return `${(meters / 1000).toFixed(1)}公里`;
    }
    return `${meters}米`;
  };

  // 格式化时间（分钟转换为小时+分钟）
  const formatDuration = (minutes: number): string => {
    const hours = Math.floor(minutes / 60);
    const mins = Math.round(minutes % 60);
    
    if (hours > 0) {
      return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`;
    }
    return `${mins}分钟`;
  };

  // 表格列定义
  const columns = [
    {
      title: '路线名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '起点',
      dataIndex: 'startLocation',
      key: 'startLocation',
      render: (location: any) => location.address
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '总距离',
      dataIndex: 'totalDistance',
      key: 'totalDistance',
      render: (distance: number) => formatDistance(distance)
    },
    {
      title: '总时间',
      dataIndex: 'totalDuration',
      key: 'totalDuration',
      render: (duration: number) => formatDuration(duration)
    },
    {
      title: '客户数量',
      dataIndex: 'points',
      key: 'customerCount',
      render: (points: any[]) => points.length
    },
    {
      title: '操作',
      key: 'action',
      render: (text: any, record: RoutePlan) => (
        <Space size="middle">
          <Button 
            icon={<EyeOutlined />} 
            type="link" 
            onClick={() => handleViewPlan(record)}
          >
            查看
          </Button>
          <Popconfirm
            title="确定要删除此路线计划吗？"
            onConfirm={() => handleDeletePlan(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button icon={<DeleteOutlined />} type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Title level={2}>路线计划历史记录</Title>
      
      <Spin spinning={loading}>
        <Card>
          {routePlans.length > 0 ? (
            <Table 
              columns={columns} 
              dataSource={routePlans}
              rowKey="id"
              pagination={{ pageSize: 10 }}
            />
          ) : (
            <Empty 
              description="暂无路线计划记录" 
              style={{ margin: '40px 0' }}
            />
          )}
        </Card>
      </Spin>
      
      <div style={{ marginTop: '20px' }}>
        <Button type="primary" onClick={() => navigate('/optimize-route')}>
          创建新路线
        </Button>
      </div>
    </div>
  );
};

export default RoutePlans; 